import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
# Create your views here.
from book.models import BookInfo


class BookListView(View):
    """
    查询所有图书、增加图书
    """

    def get(self, request):
        """
        查询所有图书
        路由：GET /books/
        """
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book = BookInfo.objects.create(
            name=book_dict.get('name'),
            pub_date=book_dict.get('pub_date')
        )

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        }, safe=False)


class BookDetailView(View):
    """
    获取单个图书信息
    修改图书信息
    删除图书
    """

    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({}, status=404)

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({}, status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.name = book_dict.get('name')
        book.pub_date = book_dict.get('pub_date')
        book.save()

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({}, status=404)

        book.delete()

        return JsonResponse({}, status=204)


# *************反序列化(将字典转换为对象)*************************

# from book.serializers import BookInfoSerializers

# book = {
#     # 'id':1,
#     'name':'从入门到放弃',
#     'pub_date':'2018-1-1',
#     'readcount':666
#
# }
# # data 反序列化(字典转对象)
# ss = BookInfoSerializers(data=book)
#
#
# # 验证数据
# # raise_exception 抛出异常信息
# ss.is_valid(raise_exception=True)


# ***********************
from book.serializers import BookInfoSerializer
from rest_framework import serializers
from book.models import BookInfo, PeopleInfo

data = {
    'name': 'django',
    'pub_date': '1999-1-1',
    'readcount': 666,
    'commentcount': 999

}

serializer = BookInfoSerializer(data=data)

serializer.is_valid(raise_exception=True)

# ******************************************
# 新增数据 保存数据
from book.serializers import BookInfoSerializer
from book.models import BookInfo, PeopleInfo

book = BookInfo.objects.get(id=5)

data = {
    'name': 'django基础',
    'pub_date': '1999-1-1',
    'readcount': 666,
    'commentcount': 555

}

serializer = BookInfoSerializer(data=data)

serializer.is_valid(raise_exception=True)

serializer.save()

# ///////////////////////////////////
from book.serializers import BookInfoSerializer
from book.models import BookInfo, PeopleInfo

# book = BookInfo.objects.get(id=1)

data = {
    'name': '射雕英雄后传传奇',
    'pub_date': '1999-1-1',
    'readcount': 666,
    'commentcount': 555

}

serializer = BookInfoSerializer(data=data)

serializer.is_valid(raise_exception=True)

serializer.save()

# *******************************************
"""修改数据"""
from book.serializers import BookInfoSerializer
from book.models import BookInfo, PeopleInfo

book = BookInfo.objects.get(id=5)

data = {
    'name': 'django基础',
    'pub_date': '1999-1-1',
    'readcount': 666,
    'commentcount': 555

}

serializer = BookInfoSerializer(instance=book, data=data)

# 默认序列化器必须传递所有required的字段，否则会抛出验证异常。但是我们可以使用partial参数来允许部分字段更新
# serializer = BookInfoSerializer(instance=book,data=
# {'pub_date':'1998-10-30','readcount':777,'commentcount':700},partial=True)

serializer.is_valid(raise_exception=True)

serializer.save()

# ****************************
# 模型类序列化器ModelSerializer
from book.serializers import BookInfoModelSerializer

BookInfoModelSerializer()

# *****************************************

from book.serializers import BookModelSerializer, PeopleInfoModelSerializer

data = {
    'book': 1,
    'name': '靖哥哥',
    'password': '123456abc',
}

sss = PeopleInfoModelSerializer(data=data)
sss.is_valid(raise_exception=True)
sss.save()

# ********************************
from book.serializers import BookModelSerializer, PeopleInfoModelSerializer

data = {
    'book_id': 1,
    'name': '靖哥哥',
    'password': '123456abc'
}

sss = PeopleInfoModelSerializer(data=data)
sss.is_valid(raise_exception=True)
sss.save()

# *******************************

from book.serializers import BookModelSerializer, PeopleInfoModelSerializer

data = {
    'book_id': 1,
    'name': '靖哥哥',
    'password': '123456abc',
    'is_delete': 1
}

sss = PeopleInfoModelSerializer(data=data)
sss.is_valid(raise_exception=True)
sss.save()

# ********************************************************


from book.serializers import BookModelSerializer, PeopleInfoModelSerializer

# data = {
#     'book_id':1,
#     'name': '靖哥哥',
#     'password': '123456abc',
#     'description': '描述',
#     'is_delete': 1
# }

data = [
    {
        'book_id': 1,
        'name': '靖妹妹～～～',
        'password': '123456abc'
    },
    {
        'book_id': 1,
        'name': '靖表哥～～～',
        'password': '123456abc'
    }
]

sss = PeopleInfoModelSerializer(data=data, many=True)
sss.is_valid(raise_exception=True)
sss.save()

# ***********************************************
# 一对多
from book.serializers import BookModelSerializer, PeopleInfoModelSerializer

data = [{
    'name': '离离原上草',
    'people': [
        {
            'name': '靖妹妹111',
            'password': '123456abc'
        },
        {
            'name': '靖表哥222',
            'password': '123456abc'
        }
    ]
}
]

sss = BookModelSerializer(data=data, many=True)
sss.is_valid(raise_exception=True)
sss.save()